package org.hang.jvm.classpath.impl;

import org.hang.jvm.classpath.Entry;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 用系统分隔符分开的类路径，分隔符因操作系统而异，比如Windows系统下是分号，在类Unix是冒号，比如
 * java -cp path\to\class;lib\a.jar;lib\b.jar;lib\c.zip
 * java -cp path/to/class:lib/a.jar:lib/b.jar:lib/c.zip
 *
 * @author 廖景航
 * @date created on 2022/2/23 下午3:59
 */
public class CompositeEntry implements Entry {

    private final List<Entry> entryList = new ArrayList<>();

    public CompositeEntry(String pathList) {
        String[] paths = pathList.split(File.pathSeparator);
        for (String path : paths) {
            entryList.add(Entry.create(path));
        }
    }

    @Override
    public byte[] readClass(String classname) throws IOException {
        for (Entry entry : entryList) {
            try {
                return entry.readClass(classname);
            } catch (Exception e) {
                // ignore
            }
        }
        throw new IOException("class not found" + classname);
    }

    @Override
    public String toString() {
        String[] strs = new String[entryList.size()];
        for (int i = 0; i < entryList.size(); i++) {
            strs[i] = entryList.get(i).toString();
        }
        return String.join(File.pathSeparator, strs);
    }
}
